<template>
    <div class="app-container">
        <!--  功能区域 -->
        <el-form ref="form" :inline="true" :model="form" label-width="80px">
            <!-- <el-form-item label="实验室名">
                <el-input v-model="form.laboratoryName" placeholder="请输入实验室名称" clearable></el-input>
            </el-form-item> -->
            <el-form-item label="预约状态">
                <el-select v-model="form.status" placeholder="选择预约状态" clearable>
                    <el-option label="待审核" value="PENDING"></el-option>
                    <el-option label="已批准" value="APPROVED"></el-option>
                    <el-option label="已拒绝" value="REJECTED"></el-option>
                    <el-option label="已取消" value="CANCELLED"></el-option>
                    <el-option label="已完成" value="COMPLETED"></el-option>
                    <el-option label="已过期" value="EXPIRED"></el-option>
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="预约日期">
                <el-date-picker v-model="form.reservationDate" type="date" placeholder="选择预约日期" 
                    value-format="yyyy-MM-dd" clearable></el-date-picker>
            </el-form-item> -->
            <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button type="info" @click="handleReset">重置</el-button>
                <el-button type="success" @click="exportToExcel">导出当前页</el-button>
                <el-button type="warning" @click="exportAllToExcel">导出全部</el-button>
            </el-form-item>
        </el-form>


        <el-table :data="list.content" style="width: 100%" element-loading-text="Loading" v-loading="listLoading"
            border>
            <el-table-column prop="laboratoryName" label="实验室名" width="180">
            </el-table-column>
            <el-table-column prop="laboratoryLocation" label="位置" width="180">
            </el-table-column>
            <el-table-column prop="laboratoryRoomNumber" label="门牌号" width="180">
            </el-table-column>
            <el-table-column prop="userName" label="预约人">
            </el-table-column>
            <el-table-column prop="userPhone" label="预约人电话">
            </el-table-column>
            <el-table-column prop="purpose" label="预约目的">
            </el-table-column>
            <el-table-column prop="description" label="预约描述">
            </el-table-column>
            <el-table-column label="预约使用设备">
                <template slot-scope="scope">
                    <span v-for="(item, index) in scope.row.equipmentInfo" :key="index">{{ item.name }} </span>
                </template>
            </el-table-column>
            <!-- 审核状态 -->
            <el-table-column prop="status" label="预约状态" :formatter="formatStatus">
                <template slot-scope="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)" disable-transitions>
                        {{ formatStatus(scope.row) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="预约时间段">
                <template slot-scope="scope">
                    <span>{{ scope.row.startTime }}</span>--
                    <span>{{ scope.row.endTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <!-- v-if="scope.row.status == 'PENDING'" -->
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="examine(scope.$index, scope.row)">取消预约</el-button>
                    <!-- <el-button type="primary" size="mini" @click="subscribe(scope.$index, scope.row)">拒绝</el-button> -->
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]" :page-size="pages.size" layout="total, sizes, prev, pager, next, jumper"
            :total="list.totalElements || 0">
        </el-pagination>

        <!-- 查看弹框1 -->
        <el-dialog title="实验室详细信息" :visible.sync="dialogVisible" width="60%">
            <div>{{ items.name }}</div>
            <div>{{ items.description }}</div>
            <div>{{ items.location }}-{{ items.roomNumber }}</div>
            <div>当前是否可用：{{ items.status == 'AVAILABLE' ? '是' : '否' }}</div>
            <div>当前是否开放预约：{{ items.isOpen ? '是' : '否' }}</div>
            <div v-for="(item, index) in items.timeSlots" :key="item.id">实验室可预约时间：{{ item.dayOfWeek }} {{
                item.startTime[0]
                }}点 - - {{ item.endTime[0] }}点 ---开放预约人数：{{ item.maxReservations }} 当前是否可预约{{ item.available == 'true' ?
                '是' :
                '否'
                }}</div>
            <div v-for="(item, index) in items.equipment" :key="item.id">实验室设备{{ item.name }} 型号：{{ item.model }} 设备简介{{
                item.description }} 数量{{ item.quantity }} </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">关闭</el-button>
                <!-- <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
            </span>
        </el-dialog>
        <!-- 预约弹框 -->
        <el-dialog title="预约实验室" :visible.sync="dialogVisible2" width="60%">
            <div>{{ items.name }}</div>
            <div>{{ items.description }}</div>
            <div>{{ items.location }}-{{ items.roomNumber }}</div>
            <div>当前是可用：{{ items.status == 'AVAILABLE' ? '是' : '否' }}</div>
            <div>当前是否开放预约：{{ items.isOpen ? '是' : '否' }}</div>
            <!-- <div v-for="(item, index) in items.timeSlots" :key="item.id">实验室可预约时间：{{ item.dayOfWeek }} {{ item.startTime[0]
        }}点 - - {{ item.endTime[0] }}点 ---开放预约人数：{{ item.maxReservations }} 当前是否可预约{{ item.available == 'true' ? '是' :
        '否'
        }}</div>
      <div v-for="(item, index) in items.equipment" :key="item.id">实验室设备{{ item.name }} 型号：{{ item.model }} 设备简介{{
        item.description }} 数量{{ item.quantity }} </div> -->

            <!-- 表单 -->
            <el-form ref="form" :model="forms" label-width="140px">
                <el-form-item label="预约原因：">
                    <el-input v-model="forms.purpose"></el-input>
                </el-form-item>
                <el-form-item label="预约用途：">
                    <el-input v-model="forms.description"></el-input>
                </el-form-item>
                <el-form-item label="选择时间段：">
                    <el-select v-model="forms.timeSlotId" placeholder="请选择活预约时间段" style="width: 100%">
                        <el-option v-for="(item, index) in timerList" :key="item.id"
                            :label="item.dayOfWeek + item.startTime[0] + '点-' + item.endTime[0] + '点'"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="具体日期：">
                    <el-date-picker @change="breaktime" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                        v-model="forms.reservationDate" style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="需要使用的设备：">
                    <el-select v-model="forms.equipmentIds" placeholder="请选择活预约时间段" style="width: 100%">
                        <el-option v-for="(item, index) in equipmentList" :key="item.id"
                            :label="item.name + item.description + item.quantity + '台'" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible2 = false">取 消</el-button>
                <el-button type="primary" @click="subscribet">预 约</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getList, getEquipmentList, getTimerList, reservations, getReservations, putReservations, getReservationsByUser, deleteReservations } from '@/api/table'
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'

export default {
    filters: {
        statusFilter(status) {
            const statusMap = {
                published: 'success',
                draft: 'gray',
                deleted: 'danger'
            }
            return statusMap[status]
        }
    },
    data() {
        return {
            list: { content: [] },
            listLoading: true,
            form: {
                laboratoryName: '',
                status: '',
                reservationDate: ''
            },
            forms: {},
            currentPage: 1,
            pages: {
                page: 0,
                size: 10
            },
            dialogVisible: false,
            dialogVisible2: false,
            items: {},
            //设备列表
            equipmentList: [],
            //可预约时间段
            timerList: []
        }
    },
    created() {
        this.fetchData()
    },
    filters: {
        trimSeconds(timeString) {
            // console.log(timeString.replace(/^(\d{2}:\d{2})(:\d{2}(\.\d+)?)?$/, '$1'));
            if (!timeString) return '';
            return timeString.replace(/^(\d{2}:\d{2})(:\d{2}(\.\d+)?)?$/, '$1');
        },
        // 相同的过滤
        dayOf(day) {
            // 遍历day，将day.dayOfWeek中相同的过滤掉只返回不同的
            let dayOfWeek = [];
            if (day.length === 0) return '';
            for (let i = 0; i < day.length; i++) {
                if (dayOfWeek.indexOf(day[i].dayOfWeek) === -1) {
                    dayOfWeek.push(day[i].dayOfWeek);
                }
            }
            return dayOfWeek.join(',');
        }
    },
    methods: {
        fetchData() {
            this.listLoading = true
            // 合并分页参数和查询参数
            const params = {
                ...this.pages,
                ...this.form
            };
            // 移除空值参数
            Object.keys(params).forEach(key => {
                if (params[key] === '' || params[key] === null || params[key] === undefined) {
                    delete params[key];
                }
            });
            
            getReservationsByUser(params).then(res => {
                this.list = res.data
                this.listLoading = false
                console.log(this.list);
            }).catch(error => {
                this.listLoading = false
                console.error('获取数据失败:', error);
                this.$message.error('获取数据失败');
            })
        },
        // 状态格式化
        formatStatus(row) {
            const statusMap = {
                'PENDING': '待审核',
                'APPROVED': '已批准',
                'REJECTED': '已拒绝',
                'CANCELLED': '已取消',
                'COMPLETED': '已完成',
                'EXPIRED': '已过期'
            };
            return statusMap[row.status] || row.status;
        },
        // 颜色格式化
        getStatusTagType(status) {
            const typeMap = {
                'PENDING': 'warning',      // 待审核 - 黄色
                'APPROVED': 'success',    // 已批准 - 绿色
                'REJECTED': 'danger',     // 已拒绝 - 红色
                'CANCELLED': 'info',      // 已取消 - 蓝色
                'COMPLETED': '',          // 已完成 - 默认灰色
                'EXPIRED': 'danger'       // 已过期 - 红色
            };
            return typeMap[status] || '';
        },
        // 取消预约
        
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pages.size = val;
            this.pages.page = 0; // 重置到第一页
            this.currentPage = 1;
            this.fetchData();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currentPage = val;
            this.pages.page = val - 1; // 后端从0开始，前端从1开始
            this.fetchData();
        },
        handleSearch() {
            // 实现查询功能
            this.pages.page = 0;
            this.currentPage = 1;
            this.fetchData();
        },
        handleReset() {
            // 重置查询条件
            this.form = {
                laboratoryName: '',
                status: '',
                reservationDate: ''
            };
            // 重置分页
            this.pages.page = 0;
            this.currentPage = 1;
            // 重新获取数据
            this.fetchData();
        },
        exportToExcel() {
            // 导出当前页Excel功能
            if (!this.list.content || this.list.content.length === 0) {
                this.$message.warning('没有数据可导出');
                return;
            }

            // 准备导出数据
            const exportData = this.list.content.map(item => ({
                '实验室名称': item.laboratoryName || '',
                '实验室位置': item.laboratoryLocation || '',
                '预约目的': item.purpose || '',
                '预约描述': item.description || '',
                '使用设备': item.equipmentInfo ? item.equipmentInfo.map(e => e.name).join(', ') : '',
                '预约状态': this.formatStatus(item),
                '开始时间': item.startTime || '',
                '结束时间': item.endTime || '',
                '预约日期': item.reservationDate || ''
            }));

            // 创建工作表
            const worksheet = XLSX.utils.json_to_sheet(exportData);
            
            // 设置列宽
            const columnWidths = [
                { wch: 15 }, // 实验室名称
                { wch: 15 }, // 实验室位置
                { wch: 20 }, // 预约目的
                { wch: 30 }, // 预约描述
                { wch: 25 }, // 使用设备
                { wch: 10 }, // 预约状态
                { wch: 12 }, // 开始时间
                { wch: 12 }, // 结束时间
                { wch: 12 }  // 预约日期
            ];
            worksheet['!cols'] = columnWidths;

            // 创建工作簿
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, '我的预约');

            // 生成文件名（包含当前时间）
            const now = new Date();
            const timestamp = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
            const fileName = `我的预约_${timestamp}.xlsx`;

            // 导出文件
            const excelBuffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
            const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            FileSaver.saveAs(blob, fileName);

            this.$message.success('导出成功');
        },
        exportAllToExcel() {
            // 导出全部数据功能
            this.$confirm('确定要导出全部预约记录吗？这可能需要一些时间。', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.exportAllData();
            }).catch(() => {
                this.$message.info('已取消导出');
            });
        },
        async exportAllData() {
            try {
                this.$message.info('正在获取全部数据，请稍候...');
                
                // 获取所有数据（不分页）
                const allDataParams = {
                    page: 0,
                    size: 10000 // 设置一个很大的数字来获取所有数据
                };
                
                const response = await getReservationsByUser(allDataParams);
                const allData = response.data.content || [];
                
                if (allData.length === 0) {
                    this.$message.warning('没有数据可导出');
                    return;
                }

                // 准备导出数据
                const exportData = allData.map(item => ({
                    '实验室名称': item.laboratoryName || '',
                    '实验室位置': item.laboratoryLocation || '',
                    '预约目的': item.purpose || '',
                    '预约描述': item.description || '',
                    '使用设备': item.equipmentInfo ? item.equipmentInfo.map(e => e.name).join(', ') : '',
                    '预约状态': this.formatStatus(item),
                    '开始时间': item.startTime || '',
                    '结束时间': item.endTime || '',
                    '预约日期': item.reservationDate || ''
                }));

                // 创建工作表
                const worksheet = XLSX.utils.json_to_sheet(exportData);
                
                // 设置列宽
                const columnWidths = [
                    { wch: 15 }, // 实验室名称
                    { wch: 15 }, // 实验室位置
                    { wch: 20 }, // 预约目的
                    { wch: 30 }, // 预约描述
                    { wch: 25 }, // 使用设备
                    { wch: 10 }, // 预约状态
                    { wch: 12 }, // 开始时间
                    { wch: 12 }, // 结束时间
                    { wch: 12 }  // 预约日期
                ];
                worksheet['!cols'] = columnWidths;

                // 创建工作簿
                const workbook = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(workbook, worksheet, '全部我的预约');

                // 生成文件名（包含当前时间）
                const now = new Date();
                const timestamp = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
                const fileName = `全部我的预约_${timestamp}.xlsx`;

                // 导出文件
                const excelBuffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
                const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                FileSaver.saveAs(blob, fileName);

                this.$message.success(`导出成功，共导出 ${allData.length} 条记录`);
            } catch (error) {
                console.error('导出失败:', error);
                this.$message.error('导出失败，请重试');
            }
        },
        // 取消预约按钮
        examine(index, row) {
            this.$confirm('确定要取消这个预约吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteReservations(row.id).then(res => {
                    console.log(res);
                    this.$message.success('取消预约成功');
                    this.fetchData(); // 刷新列表
                }).catch(error => {
                    console.error('取消预约失败:', error);
                    this.$message.error('取消预约失败，请重试');
                });
            }).catch(() => {
                this.$message.info('已取消操作');
            });
        },
        // 拒绝按钮
        subscribe(index, row) {
            putReservations(row.id, { status: 'REJECTED' }).then(res => {
                console.log(res);
                this.$message.success('操作成功');
                this.fetchData(); // 刷新列表
            }).catch(error => {
                console.error('操作失败:', error);
                this.$message.error('操作失败，请重试');
            });
        },
        // 判断选中的事件与预约时间是否冲突
        breaktime(val) {
            const date = new Date(val);
            console.log(date.getDay());
            const dayOfWeek = date.getDay();
            const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
            const weekdayStr = weekdays[dayOfWeek];

            if (!this.forms.timeSlotId) {
                this.$message.error('请先选择时间段');
                this.forms.reservationDate = '';
                return;
            }
            for (let i = 0; i < this.timerList.length; i++) {
                if (this.timerList[i].id === this.forms.timeSlotId) {
                    if (this.timerList[i].dayOfWeek !== weekdayStr) {
                        this.$message.error('所选时间段与日期不匹配');
                        this.forms.reservationDate = '';
                        return;
                    }
                }


            }
        },
        // 预约
        subscribet() {
            console.log(this.forms);
            reservations(this.forms).then(res => {
                this.$message.success('预约成功');
                this.dialogVisible2 = false; // 关闭弹框
                this.fetchData(); // 刷新列表
                // 重置表单
                this.forms = {};
            }).catch(error => {
                console.error('预约失败:', error);
                this.$message.error('预约失败，请重试');
            });
        }
    }
}
</script>
